#!/bin/zsh

ok () {
	echo "[ "${GREEN_START}"OK"${GREEN_STOP}" ]"
}

failed () {
	echo "[ "${RED_START}"FAILED"${RED_STOP}" ]"
}

install_nginx () {
	NGINX_INSTALLED=`apk list nginx| grep 'installed'`
	echo -n "installing nginx: "
	if [ -z ${NGINX_INSTALLED} ]; then
		apk add --no-cache nginx > /dev/null
		if [ $? ]; then
			ok
		else
			failed
		fi
	else
		ok 
	fi
	if [ -f /etc/nginx/http.d/default.conf ]; then
		rm /etc/nginx/http.d/default.conf 
		if [ -f /srv/podman/openldap/phpldapadmin/phpldapadmin.conf ]; then
			cp /srv/podman/openldap/phpldapadmin/phpldapadmin.conf /etc/nginx/http.d/phpldapadmin.conf  
		fi
	fi
}

start_nginx () {
	echo -n "starting service nginx: "
	NGINX_INSTALLED=`apk list nginx`
	if [ -z ${NGINX_INSTALLED} ]; then
		install_nginx
	fi
	if [ ! -f /etc/ssh/ssh_host_rsa_key ]; then
		ssh-keygen -A >> ${LOG_FILE}
	fi
	PID=`ps aux | grep '/usr/sbin/nginx' | sed '/grep/d'`
	if [ -z ${PID} ]; then
		/usr/sbin/nginx  && ok || failed
	else
		ok
	fi
}

status_nginx () {
	echo -n "status of service nginx: "
	PID=`ps aux | grep '/usr/sbin/nginx' | sed '/grep/d'`
	[ -z ${PID} ] && failed || ok
}

reload_nginx () {
	echo -n "reload service nginx: "
	/usr/sbin/nginx -s reload && ok || failed
}

main () {
	if [ $# -gt 0 ]; then
		action=$1
	else
		action=status
	fi
	# echo "action = ${action}"
	case $action in 
		install)
			install_nginx
			;;
		status)
			status_nginx
			;;
		start)
			start_nginx
			;;
		reload)
			reload_nginx
			;;
		*)
			;;
	esac 
}

main $@

# vim: ts=4 sw=4
